package parsing.yago;

import core.objects.Book;
import core.objects.Author;

public class LiteralFactsParser extends YagoFileParser {

	private static final String LITERAL_FACTS = "yagoLiteralFacts.tsv";	
	private static final int ESTIMATED_LINES_NUM = 3353660;

	private static final String YAGO_ISBN = "^^yagoISBN";	
	
	private static final String HAS_PAGES = "hasPages";
	private static final String HAS_ISBN = "hasISBN";
	private static final String WAS_CREATED_ON_DATE = "wasCreatedOnDate";
	private static final String WAS_BORN_ON_DATE = "wasBornOnDate";
	private static final String DIED_ON_DATE = "diedOnDate";
	
	protected LiteralFactsParser(String directory) {
		super(directory);
	}

	@Override
	protected String getFileName() {
		return LITERAL_FACTS;
	}

	@Override
	protected int getEstimatedFileLinesNumber() {
		return ESTIMATED_LINES_NUM;
	}
	
	@Override
	protected void handleLineParsing(String[] line) {
		
		/*line is <weird-id> <...> <hasISBN / diedIn / ..> ""^^v vv */
		
		if (line[2].equals(WAS_BORN_ON_DATE) && line.length == 5) {
			
			Author writer = ParsingEnvironment.getWriters().get(line[1]);
			if (writer != null) {
				writer.setBirthday(parseDate(line[4]));
			}
			
		} else if (line[2].equals(DIED_ON_DATE) && line.length == 5) {
			
			Author writer = ParsingEnvironment.getWriters().get(line[1]);
			if (writer != null) {
				writer.setDeathday(parseDate(line[4]));
			}
			
		} else if (line[2].equals(HAS_ISBN)) {
			
			Book book = ParsingEnvironment.getBooks().get(line[1]);
			if (book != null) {
				book.setISBN(extractISBN(line[3]));
			}
		} else if (line[2].equals(HAS_PAGES)) {
			
			Book book = ParsingEnvironment.getBooks().get(line[1]);
			if (book != null) {
				try {
					book.setNumOfPages(Integer.parseInt(line[4]));
				} catch (NumberFormatException e) {
					//do nothing, keep on parsing, this book will not have numOfPages
				}
			}
		} else if (line[2].equals(WAS_CREATED_ON_DATE)) {
			
			//line[3] equals a frightening "1960-00-00"^^xsd:date, how ever
			//line[4] equals a more pleasant "1960.0000"
			
			Book book = ParsingEnvironment.getBooks().get(line[1]);
			if (book != null) {
				book.setReleaseYear(parseDate(line[4]));
			}
		}
	}

	@Override
	protected boolean isLineFromFileOkay(String[] line) {
		return (line.length > 3 && line.length < 6);
	}
	
	private String extractISBN(String part) {
		
		/* ISBN in YAGO would be of the form "??-???-?-??"^^yagoISBN
		 * so we'll remove the ugliness aroun the number. Sadly,
		 * the last part of the line in LiteralFacts which gives
		 * the value is too many times 0 instead of the actual ISBN
		 * which can be found in this ugly part :( ... */
		part = part.replace(YAGO_ISBN, "");
		part = part.replace("\"", "");
		part = part.replace("-", "");
				
		return part;
	}


}
